<?php
class Admincp_BlockController extends Main_Controller_Action
{
    private $_arrParam;
    private $_model;
    private $_locale;

    public function init()
    {
        $this->loadTemplates('admin');
        $this->view->headTitle('Quản lý nội dung');
        $this->_arrParam = $this->_request->getParams();
        $this->_model = new Admincp_Model_Block();
        $this->_locale = 'vi';
    }

    public function preDispatch()
    {
        $auth = Zend_Auth::getInstance();
        if(!$auth->hasIdentity()) {
            if($this->_request->getActionName() != 'login')
                $this->_redirect('admincp/index/login');
        }
    }

    public function indexAction()
    {
        $adapter = new Zend_Paginator_Adapter_DbSelect($this->_model->listBlock($this->_locale));
        $paginator = new Zend_Paginator($adapter);
        $paginator->setItemCountPerPage(40);
        $paginator->setPageRange(5);
        $currentPage = $this->_request->getParam('page', 1);
        $paginator->setCurrentPageNumber($currentPage);
        $this->view->data = $paginator;
        $this->view->total = $paginator->getTotalItemCount();
    }

    public function editAction()
    {
        $id = (int) $this->_arrParam['id'];
        $this->view->data = $this->_model->getBlockById($id);
        $this->view->id = $id;
        $language = new Admincp_Model_Language();
        $this->view->language = $language->listLanguageFull();

        if($this->_request->isPost()) {
            $description['vi'] = trim(stripslashes($this->_arrParam['description-vi']));
            $description['zh'] = trim(stripslashes($this->_arrParam['description-zh']));
            $description['en'] = trim(stripslashes($this->_arrParam['description-en']));
            $description['trv'] = trim(stripslashes($this->_arrParam['description-trv']));

            foreach($description as $key=>$value) {
                foreach($this->view->language as $lang) {
                    if($key == $lang['locale']) {
                        $data = array(
                            'language_id'=>$lang['id'],
                            'description'=>$value,
                        );
                        $this->_model->updateBlockLanguage($data, $id);
                        break;
                    }
                }
            }
            $this->_redirect('admincp/block');
        }
    }
}
